# -*- coding: utf-8 -*-
# File : app.py
# Author: taoyahui
# Date : 2022/6/13

# 这是用于规范flask主架构
from flask import Flask, request, jsonify, render_template
import database_services
import requests
import re
app = Flask(__name__) # 创建一个Flask对象

@app.route('/database/change', methods=['POST'])
def data_change():
    """
    数据库修改
    :return:
    """
    input = request.json
    field_number = input['field_number']
    value = input['value']
    student_id = input['student_id']
    return jsonify(database_services.data_change(field_number, value, student_id))


@app.route('/database/show')
def data_show():
    return jsonify(database_services.data_show())


@app.route('/database/add', methods=['POST'])
def data_add():
    input = request.json
    name = input["name"]
    gender = input["gender"]
    student_id = input["student_id"]
    class_name = input["class_name"]
    college_name = input["college_name"]
    database_services.execSQL("insert into student values(null,'%s','%s','%s','%s','%s')" % (
        name, gender, student_id, class_name, college_name))
    print("插入成功！")
    # 执行数据查询，验证新增的数据是否已经添加到数据库的student表中
    return jsonify(database_services.data_show())

@app.route('/login', methods=['POST', 'GET'])
def login():
    """
    登录相关功能实现
    :return:
    """
    if request.method == 'POST':
        # 当请求为POST方法时触发
        username = request.form['username']
        password = request.form['password']
        user = database_services.execSQL(f"select * from user where username = '{username}'")
        if user[0][1] == password:
            blogs = database_services.execSQL("select id, title from blogs")
            return render_template('blog_list.html', blogs=blogs)
        else:
            return render_template('login.html', msg='账户或密码错误')
    else:
        # 如果请求不是POST的话触发
        return render_template('login.html')

@app.route("/crawler")
def crawler():
    """
    创建一个数据爬取的接口
    :return:
    """
    response = requests.get('http://10.10.74.125/problemset.php')
    html = response.text
    print('html显示的内容为:')
    print(html)
    print("*" * 100)

    # 获取到了对应的标题名称
    pattern = re.compile("<a href='problem.php\?id=\d+'>(.*?)</a>")
    result = pattern.findall(html)
    # res_list = []
    # for r in result:
    #     res_list.append(r)
    return jsonify(result)


@app.route("/my_plot")
def my_plot():
    import matplotlib.pyplot as plt

    # x坐标数据
    x_data = [1, 2, 3, 4, 5, 6]
    # y坐标数据
    y_data = [1, 2, 4, 8, 16, 32]

    plt.plot(x_data, y_data)
    plt.show()
    plt.close()
    return "ok"


@app.route("/my_bar")
def my_bar():
    import matplotlib.pyplot as plt

    x_data = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    y_data = [5, 20, 36, 10, 75, 90]
    plt.bar(x_data, y_data)
    plt.rcParams['font.sans-serif'] = ['SimHei']

    plt.show()
    plt.close()

@app.route('/')
def root():
    return "Hello World"


if __name__ == '__main__':
    app.run(host='0.0.0.0')
